[코담]
웹개발·실전 프로젝트·AI까지, 파이썬·장고의 모든것을 담아낸 강의와 개발 노트
카페 주문 데이터 분석 API | ✅저자: 이유정(박사)
시나리오
- 매일 아침 로컬에 저장된
orders_data.json
파일을 읽어, - 운영팀은 아래 두 가지 정보를 대시보드에서 확인하고자 합니다:
요구 API
- 요일별 매출 합계 (월~일)
- 상품별 평균 판매 단가 (단가 = 총매출 ÷ 총수량)
원시데이터 orders_data.json
[
{ "order_id": "C1001", "product": "아메리카노", "price": 4000, "quantity": 2, "order_date": "2025-06-15" },
{ "order_id": "C1002", "product": "라떼", "price": 4500, "quantity": 1, "order_date": "2025-06-15" },
{ "order_id": "C1003", "product": "아메리카노", "price": 4000, "quantity": 1, "order_date": "2025-06-16" }
]
sales/utils.py
— JSON 파일 로드 함수
import os
import json
from django.conf import settings
from datetime import datetime
def load_orders():
"""orders_data.json 파일을 읽어 Python 리스트로 반환"""
path = os.path.join(settings.______, 'orders_data.json')
with open(path, encoding='utf-8') as f:
data = json.____(f)
return data
sales/views.py
— API 뷰 함수 2개 작성
from django.http import JsonResponse
from .utils import load_orders
from datetime import datetime
def revenue_by_weekday(request):
"""
요일별 매출 합계 API
결과 예시: [{"weekday": "Monday", "revenue": 8000}, …]
"""
data = load_orders()
result = {} # {"Monday": 8000, ...}
for item in data:
date = item["____"]
weekday = datetime.strptime(date, "%Y-%m-%d").strftime("____")
sales = item["price"] * item["quantity"]
if weekday in result:
result[weekday] += sales
else:
result[weekday] = ____
response = [{"weekday": k, "revenue": v} for k, v in sorted(result.items())]
return JsonResponse(response, safe=____)
def product_unit_price_average(request):
"""
상품별 평균 판매 단가 API
예시 결과: [{"product": "아메리카노", "unit_price": 4000.0}, …]
"""
data = load_orders()
total_price = {} # {"아메리카노": 12000}
total_qty = {} # {"아메리카노": 3}
for item in data:
product = item["product"]
price = item["price"] * item["quantity"]
qty = item["quantity"]
total_price[product] = total_price.get(product, 0) + price
total_qty[product] = total_qty.get(product, 0) + qty
response = []
for product in sorted(total_price.keys()):
avg = total_price[product] / total_qty[product]
response.append({"product": product, "unit_price": round(avg, 1)})
return JsonResponse(response, safe=____)
sales/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('orders/weekday/', views.revenue_by_weekday),
path('orders/unitprice/', views.product_unit_price_average),
]
의사코드
- 요일별 매출 합계 API
1. JSON 로드 → data = load_orders()
2. 빈 딕셔너리 result = {}
3. 각 주문 항목(item)에 대해 반복:
- item["order_date"]를 datetime 객체로 변환 → 요일 추출 (예: "Monday")
- 매출액 계산: item["price"] * item["quantity"]
- result[weekday] += 매출 누적
4. result를 리스트로 변환해 JsonResponse로 응답
상품별 평균 판매 단가 API
1. JSON 로드 → data = load_orders()
2. 두 딕셔너리:
- total_price: 상품별 총매출
- total_qty: 상품별 총수량
3. 각 주문 항목(item)에 대해 반복:
- item["product"]로 그룹화
- 총매출 += item["price"] * item["quantity"]
- 총수량 += item["quantity"]
4. 평균 단가 = 총매출 / 총수량
5. 소수점 1자리로 반올림해 JsonResponse로 응답
✅ Insomnia 테스트 결과
GET /orders/weekday/
[{ "weekday": "Monday", "revenue": 8500 }]
GET /orders/unitprice/
[{ "product": "아메리카노", "unit_price": 4000.0 }]
✅ 정답
utils.py
path = os.path.join(settings.BASE_DIR, 'orders_data.json')
data = json.load(f)
views.py
date = item["order_date"]
weekday = datetime.strptime(date, "%Y-%m-%d").strftime("%A")
result[weekday] = sales
safe=False